package com.kun.base.ui

import java.util.*

/**
 *
 * activity堆栈管理，先入后出，创建activity时压入，销毁activity时移出
 *
 *  @author : Kun
 *  @date : 2021/4/13
 *  @time : 16:53
 */
object ActivityStack {
    private val activites: Stack<BaseActivity>? = Stack()
    private var stubIdx = Int.MAX_VALUE

    /**
     * 关闭activity，并从堆栈中移除
     */
    fun finish(activity: BaseActivity?) {
        var activity = activity
        if (activity != null) {
            activity.finish()
            // 从堆栈中移除
            activites!!.remove(activity)
            activity = null
        }
    }

    /**
     * 获取的栈顶的activity 移除
     */
    val topActivity: BaseActivity?
        get() = if (!activites!!.isEmpty()) {
            activites.pop()
        } else null

    /**
     * 获取的栈底的activity
     */
    val lastActivity: BaseActivity?
        get() = if (!activites!!.isEmpty()) {
            activites.lastElement()
        } else null

    /**
     * 移除栈顶的activity
     */
    @Synchronized
    fun pop(activity: BaseActivity?) {
        if (activity != null && activites!!.size > 0) {
            activites.remove(activity)
        }
    }

    /**
     * 返回栈顶的第几个activity(不移除)
     */
    fun getLastActivityAt(index: Int): BaseActivity? {
        return if (index > 0 && index < activites!!.size) {
            activites.elementAt(activites.size - index)
        } else null
    }

    /**
     * 返回栈顶activity(不移除)
     */
    val topActivityNoRemove: BaseActivity?
        get() = if (activites!!.empty()) {
            null
        } else activites.elementAt(activites.size - 1)

    fun findActivity(clazz: String?): BaseActivity? {
        if (clazz == null) {
            return null
        }
        for (i in activites!!.indices.reversed()) {
            val activity = activites.elementAt(i)
            if (clazz == activity.javaClass.name) {
                return activity
            }
        }
        return null
    }

    /**
     * 往栈中压入activity
     */
    fun push(activity: BaseActivity?) {
        if (activity != null && null != activites) {
            activites.push(activity)
        }
    }

    /**
     * 销毁栈的activity,并清空栈
     */
    fun finishAll() {
        while (!activites!!.isEmpty()) {
            finish(topActivityNoRemove)
        }
        activites.clear()
    }

    /**
     * 销毁栈顶的若干activity
     */
    fun finishStubTop() {
        while (size() > stubIdx) {
            finish(topActivity)
        }
        stubIdx = Int.MAX_VALUE
    }

    fun tagStub() {
        stubIdx = size()
    }

    /**
     * 获取栈的大小
     */
    fun size(): Int {
        return activites?.size ?: 0
    }

    val activityList: ArrayList<BaseActivity>
        get() = ArrayList(activites)
}